package com.car.rental.user.controller;

import com.car.rental.common.core.exception.BusinessException;
import com.car.rental.common.core.response.ResponseResult;
import com.car.rental.common.utils.JwtUtils;
import com.car.rental.user.model.request.DriverLicenseRequest;
import com.car.rental.user.model.response.DriverLicenseResponse;
import com.car.rental.user.service.DriverLicenseService;
import com.car.rental.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.util.List;

import com.car.rental.user.constant.DriverLicenseStatus;

@Validated
@RestController
@RequestMapping("/driver-license")
@RequiredArgsConstructor
public class DriverLicenseController {

    private final DriverLicenseService driverLicenseService;
    private final UserService userService;
    private final JwtUtils jwtUtils;

    /**
     * 提交驾驶证认证
     */
    @PostMapping
    public ResponseResult<Void> submitLicense(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "file", required = true) MultipartFile file,
            @RequestParam("licenseNumber") String licenseNumber,
            @RequestParam("name") String name,
            @RequestParam("issueDate") String issueDate,
            @RequestParam("expireDate") String expireDate,
            @RequestParam("licenseClass") String licenseClass) {
        Long userId = jwtUtils.getUserIdFromToken(token.substring(7));
        
        // 先上传图片
        ResponseResult<String> uploadResult = driverLicenseService.uploadLicenseImage(userId, file);
        
        // 构建认证请求
        DriverLicenseRequest request = new DriverLicenseRequest();
        request.setLicenseNumber(licenseNumber);
        request.setName(name);
        request.setIssueDate(LocalDate.parse(issueDate));
        request.setExpireDate(LocalDate.parse(expireDate));
        request.setLicenseClass(licenseClass);
        request.setImageUrl(uploadResult.getData());
        
        // 设置认证状态为认证中
        request.setStatus(DriverLicenseStatus.PENDING.getCode());  // 1-认证中
        request.setRemark(DriverLicenseStatus.PENDING.getRemark()); // "认证中"
        
        // 提交认证
        return driverLicenseService.submitLicense(userId, request);
    }

    /**
     * 获取驾驶证信息
     */
    @GetMapping("/{userId}")
    public ResponseResult<List<DriverLicenseResponse>> getLicenseInfo(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId) {
        // 从token中获取用户ID
        Long currentUserId = jwtUtils.getUserIdFromToken(token.substring(7));
        
        // 验证权限（只能查看自己的驾驶证信息）
        if (!currentUserId.equals(userId)) {
            throw new BusinessException("无权查看他人驾驶证信息");
        }
        
        return driverLicenseService.getLicenseInfo(userId);
    }

    /**
     * 更新驾驶证认证状态（管理员接口）
     */
    @PutMapping("/{userId}/status/{licenseNumber}")
    public ResponseResult<Void> updateLicenseStatus(
            @PathVariable Long userId,
            @PathVariable String licenseNumber,
            @NotNull(message = "状态不能为空") @RequestParam Integer status,
            @RequestParam(required = false) String remark) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long currentUserId = (Long) authentication.getPrincipal();
        if (!userService.checkAdminRole(currentUserId)) {
            throw new BusinessException("需要管理员权限");
        }
        return driverLicenseService.updateLicenseStatus(userId, licenseNumber, status, remark);
    }

    /**
     * 检查用户是否已通过驾驶证认证
     */
    @GetMapping("/{userId}/verify")
    public ResponseResult<Boolean> checkLicenseVerified(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId) {
        validatePermission(token, userId);
        return driverLicenseService.checkLicenseVerified(userId);
    }

    /**
     * 更新驾驶证信息
     */
    @PutMapping("/{userId}")
    public ResponseResult<Void> updateLicense(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestParam("licenseNumber") String licenseNumber,
            @RequestParam("name") String name,
            @RequestParam("issueDate") String issueDate,
            @RequestParam("expireDate") String expireDate,
            @RequestParam("licenseClass") String licenseClass,
            @RequestParam(value = "imageUrl", required = false) String imageUrl) {
        validatePermission(token, userId);
        
        // 构建认证请求
        DriverLicenseRequest request = new DriverLicenseRequest();
        request.setLicenseNumber(licenseNumber);
        request.setName(name);
        request.setIssueDate(LocalDate.parse(issueDate));
        request.setExpireDate(LocalDate.parse(expireDate));
        request.setLicenseClass(licenseClass);
        
        // 如果上传了新图片，先处理图片
        if (file != null) {
            ResponseResult<String> uploadResult = driverLicenseService.uploadLicenseImage(userId, file);
            request.setImageUrl(uploadResult.getData());
        } else {
            // 如果没有上传新图片，使用原来的图片URL
            request.setImageUrl(imageUrl);
        }
        
        // 设置认证状态为认证中
        request.setStatus(DriverLicenseStatus.PENDING.getCode());
        request.setRemark(DriverLicenseStatus.PENDING.getRemark());
        
        return driverLicenseService.updateLicense(userId, request);
    }

    /**
     * 获取所有驾驶证列表（管理员接口）
     */
    @GetMapping("/list")
    public ResponseResult<List<DriverLicenseResponse>> getAllLicenses(
            @RequestHeader("Authorization") String token) {
        // 验证管理员权限
        Long currentUserId = jwtUtils.getUserIdFromToken(token.substring(7));
        if (!userService.checkAdminRole(currentUserId)) {
            throw new BusinessException("需要管理员权限");
        }
        return driverLicenseService.getAllLicenses();
    }

    /**
     * 验证用户权限
     */
    private void validatePermission(String token, Long userId) {
        Long currentUserId = jwtUtils.getUserIdFromToken(token.substring(7));
        if (!currentUserId.equals(userId)) {
            throw new BusinessException("无权操作");
        }
    }
} 